6533daec9836b7ddc89a9b49d68f9cf887573de4
3 * @defgroup FileRepo File Repository
5 * @brief This module handles how MediaWiki interacts with filesystems.
11 * Base code for file repositories.
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
33 * Base class for file repositories
38 const DELETE_SOURCE
= 1;
40 const OVERWRITE_SAME
= 4;
41 const SKIP_LOCKING
= 8;
43 /** @var FileBackend */
45 /** @var Array Map of zones to config */
46 protected $zones = array();
48 var $thumbScriptUrl, $transformVia404;
49 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
50 var $fetchDescription, $initialCapital;
51 var $pathDisclosureProtection = 'simple'; // 'paranoid'
52 var $descriptionCacheExpiry, $url, $thumbUrl;
53 var $hashLevels, $deletedHashLevels;
56 * Factory functions for creating new files
57 * Override these in the base class
59 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
60 var $oldFileFactory = false;
61 var $fileFactoryKey = false, $oldFileFactoryKey = false;
63 function __construct( array $info = null ) {
64 // Verify required settings presence
67 ||
!array_key_exists( 'name', $info )
68 ||
!array_key_exists( 'backend', $info )
70 throw new MWException( __CLASS__
. " requires an array of options having both 'name' and 'backend' keys.\n" );
74 $this->name
= $info['name'];
75 if ( $info['backend'] instanceof FileBackend
) {
76 $this->backend
= $info['backend']; // useful for testing
78 $this->backend
= FileBackendGroup
::singleton()->get( $info['backend'] );
81 // Optional settings that can have no value
82 $optionalSettings = array(
83 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
84 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
87 foreach ( $optionalSettings as $var ) {
88 if ( isset( $info[$var] ) ) {
89 $this->$var = $info[$var];
93 // Optional settings that have a default
94 $this->initialCapital
= isset( $info['initialCapital'] )
95 ?
$info['initialCapital']
96 : MWNamespace
::isCapitalized( NS_FILE
);
97 $this->url
= isset( $info['url'] )
99 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
100 if ( isset( $info['thumbUrl'] ) ) {
101 $this->thumbUrl
= $info['thumbUrl'];
103 $this->thumbUrl
= $this->url ?
"{$this->url}/thumb" : false;
105 $this->hashLevels
= isset( $info['hashLevels'] )
106 ?
$info['hashLevels']
108 $this->deletedHashLevels
= isset( $info['deletedHashLevels'] )
109 ?
$info['deletedHashLevels']
111 $this->transformVia404
= !empty( $info['transformVia404'] );
112 $this->zones
= isset( $info['zones'] )
115 // Give defaults for the basic zones...
116 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
117 if ( !isset( $this->zones
[$zone] ) ) {
118 $this->zones
[$zone] = array(
119 'container' => "{$this->name}-{$zone}",
120 'directory' => '' // container root
127 * Get the file backend instance. Use this function wisely.
129 * @return FileBackend
131 public function getBackend() {
132 return $this->backend
;
136 * Get an explanatory message if this repo is read-only.
137 * This checks if an administrator disabled writes to the backend.
139 * @return string|bool Returns false if the repo is not read-only
141 public function getReadOnlyReason() {
142 return $this->backend
->getReadOnlyReason();
146 * Check if a single zone or list of zones is defined for usage
148 * @param $doZones Array Only do a particular zones
151 protected function initZones( $doZones = array() ) {
152 $status = $this->newGood();
153 foreach ( (array)$doZones as $zone ) {
154 $root = $this->getZonePath( $zone );
155 if ( $root === null ) {
156 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
163 * Take all available measures to prevent web accessibility of new deleted
164 * directories, in case the user has not configured offline storage
169 protected function initDeletedDir( $dir ) {
170 $this->backend
->secure( // prevent web access & dir listings
171 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
175 * Determine if a string is an mwrepo:// URL
180 public static function isVirtualUrl( $url ) {
181 return substr( $url, 0, 9 ) == 'mwrepo://';
185 * Get a URL referring to this repository, with the private mwrepo protocol.
186 * The suffix, if supplied, is considered to be unencoded, and will be
187 * URL-encoded before being returned.
189 * @param $suffix string
192 public function getVirtualUrl( $suffix = false ) {
193 $path = 'mwrepo://' . $this->name
;
194 if ( $suffix !== false ) {
195 $path .= '/' . rawurlencode( $suffix );
201 * Get the URL corresponding to one of the four basic zones
203 * @param $zone String: one of: public, deleted, temp, thumb
204 * @return String or false
206 public function getZoneUrl( $zone ) {
211 return "{$this->url}/temp";
213 return false; // no public URL
215 return $this->thumbUrl
;
222 * Get the backend storage path corresponding to a virtual URL.
223 * Use this function wisely.
228 public function resolveVirtualUrl( $url ) {
229 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
230 throw new MWException( __METHOD__
.': unknown protocol' );
232 $bits = explode( '/', substr( $url, 9 ), 3 );
233 if ( count( $bits ) != 3 ) {
234 throw new MWException( __METHOD__
.": invalid mwrepo URL: $url" );
236 list( $repo, $zone, $rel ) = $bits;
237 if ( $repo !== $this->name
) {
238 throw new MWException( __METHOD__
.": fetching from a foreign repo is not supported" );
240 $base = $this->getZonePath( $zone );
242 throw new MWException( __METHOD__
.": invalid zone: $zone" );
244 return $base . '/' . rawurldecode( $rel );
248 * The the storage container and base path of a zone
250 * @param $zone string
251 * @return Array (container, base path) or (null, null)
253 protected function getZoneLocation( $zone ) {
254 if ( !isset( $this->zones
[$zone] ) ) {
255 return array( null, null ); // bogus
257 return array( $this->zones
[$zone]['container'], $this->zones
[$zone]['directory'] );
261 * Get the storage path corresponding to one of the zones
263 * @param $zone string
264 * @return string|null Returns null if the zone is not defined
266 public function getZonePath( $zone ) {
267 list( $container, $base ) = $this->getZoneLocation( $zone );
268 if ( $container === null ||
$base === null ) {
271 $backendName = $this->backend
->getName();
272 if ( $base != '' ) { // may not be set
275 return "mwstore://$backendName/{$container}{$base}";
279 * Create a new File object from the local repository
281 * @param $title Mixed: Title object or string
282 * @param $time Mixed: Time at which the image was uploaded.
283 * If this is specified, the returned object will be an
284 * instance of the repository's old file class instead of a
285 * current file. Repositories not supporting version control
286 * should return false if this parameter is set.
287 * @return File|null A File, or null if passed an invalid Title
289 public function newFile( $title, $time = false ) {
290 $title = File
::normalizeTitle( $title );
295 if ( $this->oldFileFactory
) {
296 return call_user_func( $this->oldFileFactory
, $title, $this, $time );
301 return call_user_func( $this->fileFactory
, $title, $this );
306 * Find an instance of the named file created at the specified time
307 * Returns false if the file does not exist. Repositories not supporting
308 * version control should return false if the time is specified.
310 * @param $title Mixed: Title object or string
311 * @param $options array Associative array of options:
312 * time: requested time for a specific file version, or false for the
313 * current version. An image object will be returned which was
314 * created at the specified time (which may be archived or current).
316 * ignoreRedirect: If true, do not follow file redirects
318 * private: If true, return restricted (deleted) files if the current
319 * user is allowed to view them. Otherwise, such files will not
321 * @return File|bool False on failure
323 public function findFile( $title, $options = array() ) {
324 $title = File
::normalizeTitle( $title );
328 $time = isset( $options['time'] ) ?
$options['time'] : false;
329 # First try the current version of the file to see if it precedes the timestamp
330 $img = $this->newFile( $title );
334 if ( $img->exists() && ( !$time ||
$img->getTimestamp() == $time ) ) {
337 # Now try an old version of the file
338 if ( $time !== false ) {
339 $img = $this->newFile( $title, $time );
340 if ( $img && $img->exists() ) {
341 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
342 return $img; // always OK
343 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
350 if ( !empty( $options['ignoreRedirect'] ) ) {
353 $redir = $this->checkRedirect( $title );
354 if ( $redir && $title->getNamespace() == NS_FILE
) {
355 $img = $this->newFile( $redir );
359 if ( $img->exists() ) {
360 $img->redirectedFrom( $title->getDBkey() );
368 * Find many files at once.
370 * @param $items array An array of titles, or an array of findFile() options with
371 * the "title" option giving the title. Example:
373 * $findItem = array( 'title' => $title, 'private' => true );
374 * $findBatch = array( $findItem );
375 * $repo->findFiles( $findBatch );
378 public function findFiles( array $items ) {
380 foreach ( $items as $item ) {
381 if ( is_array( $item ) ) {
382 $title = $item['title'];
384 unset( $options['title'] );
389 $file = $this->findFile( $title, $options );
391 $result[$file->getTitle()->getDBkey()] = $file;
398 * Find an instance of the file with this key, created at the specified time
399 * Returns false if the file does not exist. Repositories not supporting
400 * version control should return false if the time is specified.
402 * @param $sha1 String base 36 SHA-1 hash
403 * @param $options array Option array, same as findFile().
404 * @return File|bool False on failure
406 public function findFileFromKey( $sha1, $options = array() ) {
407 $time = isset( $options['time'] ) ?
$options['time'] : false;
408 # First try to find a matching current version of a file...
409 if ( $this->fileFactoryKey
) {
410 $img = call_user_func( $this->fileFactoryKey
, $sha1, $this, $time );
412 return false; // find-by-sha1 not supported
414 if ( $img && $img->exists() ) {
417 # Now try to find a matching old version of a file...
418 if ( $time !== false && $this->oldFileFactoryKey
) { // find-by-sha1 supported?
419 $img = call_user_func( $this->oldFileFactoryKey
, $sha1, $this, $time );
420 if ( $img && $img->exists() ) {
421 if ( !$img->isDeleted( File
::DELETED_FILE
) ) {
422 return $img; // always OK
423 } elseif ( !empty( $options['private'] ) && $img->userCan( File
::DELETED_FILE
) ) {
432 * Get an array or iterator of file objects for files that have a given
433 * SHA-1 content hash.
438 public function findBySha1( $hash ) {
443 * Get the public root URL of the repository
447 public function getRootUrl() {
452 * Get the URL of thumb.php
456 public function getThumbScriptUrl() {
457 return $this->thumbScriptUrl
;
461 * Returns true if the repository can transform files via a 404 handler
465 public function canTransformVia404() {
466 return $this->transformVia404
;
470 * Get the name of an image from its title object
472 * @param $title Title
475 public function getNameFromTitle( Title
$title ) {
477 if ( $this->initialCapital
!= MWNamespace
::isCapitalized( NS_FILE
) ) {
478 $name = $title->getUserCaseDBKey();
479 if ( $this->initialCapital
) {
480 $name = $wgContLang->ucfirst( $name );
483 $name = $title->getDBkey();
489 * Get the public zone root storage directory of the repository
493 public function getRootDirectory() {
494 return $this->getZonePath( 'public' );
498 * Get a relative path including trailing slash, e.g. f/fa/
499 * If the repo is not hashed, returns an empty string
501 * @param $name string Name of file
504 public function getHashPath( $name ) {
505 return self
::getHashPathForLevel( $name, $this->hashLevels
);
509 * Get a relative path including trailing slash, e.g. f/fa/
510 * If the repo is not hashed, returns an empty string
512 * @param $suffix string Basename of file from FileRepo::storeTemp()
515 public function getTempHashPath( $suffix ) {
516 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
517 $name = isset( $parts[1] ) ?
$parts[1] : $suffix; // hash path is not based on timestamp
518 return self
::getHashPathForLevel( $name, $this->hashLevels
);
526 protected static function getHashPathForLevel( $name, $levels ) {
527 if ( $levels == 0 ) {
530 $hash = md5( $name );
532 for ( $i = 1; $i <= $levels; $i++
) {
533 $path .= substr( $hash, 0, $i ) . '/';
540 * Get the number of hash directory levels
544 public function getHashLevels() {
545 return $this->hashLevels
;
549 * Get the name of this repository, as specified by $info['name]' to the constructor
553 public function getName() {
558 * Make an url to this repo
560 * @param $query mixed Query string to append
561 * @param $entry string Entry point; defaults to index
562 * @return string|bool False on failure
564 public function makeUrl( $query = '', $entry = 'index' ) {
565 if ( isset( $this->scriptDirUrl
) ) {
566 $ext = isset( $this->scriptExtension
) ?
$this->scriptExtension
: '.php';
567 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
573 * Get the URL of an image description page. May return false if it is
574 * unknown or not applicable. In general this should only be called by the
575 * File class, since it may return invalid results for certain kinds of
576 * repositories. Use File::getDescriptionUrl() in user code.
578 * In particular, it uses the article paths as specified to the repository
579 * constructor, whereas local repositories use the local Title functions.
581 * @param $name string
584 public function getDescriptionUrl( $name ) {
585 $encName = wfUrlencode( $name );
586 if ( !is_null( $this->descBaseUrl
) ) {
587 # "http://example.com/wiki/Image:"
588 return $this->descBaseUrl
. $encName;
590 if ( !is_null( $this->articleUrl
) ) {
591 # "http://example.com/wiki/$1"
593 # We use "Image:" as the canonical namespace for
594 # compatibility across all MediaWiki versions.
595 return str_replace( '$1',
596 "Image:$encName", $this->articleUrl
);
598 if ( !is_null( $this->scriptDirUrl
) ) {
599 # "http://example.com/w"
601 # We use "Image:" as the canonical namespace for
602 # compatibility across all MediaWiki versions,
603 # and just sort of hope index.php is right. ;)
604 return $this->makeUrl( "title=Image:$encName" );
610 * Get the URL of the content-only fragment of the description page. For
611 * MediaWiki this means action=render. This should only be called by the
612 * repository's file class, since it may return invalid results. User code
613 * should use File::getDescriptionText().
615 * @param $name String: name of image to fetch
616 * @param $lang String: language to fetch it in, if any.
619 public function getDescriptionRenderUrl( $name, $lang = null ) {
620 $query = 'action=render';
621 if ( !is_null( $lang ) ) {
622 $query .= '&uselang=' . $lang;
624 if ( isset( $this->scriptDirUrl
) ) {
625 return $this->makeUrl(
627 wfUrlencode( 'Image:' . $name ) .
630 $descUrl = $this->getDescriptionUrl( $name );
632 return wfAppendQuery( $descUrl, $query );
640 * Get the URL of the stylesheet to apply to description pages
642 * @return string|bool False on failure
644 public function getDescriptionStylesheetUrl() {
645 if ( isset( $this->scriptDirUrl
) ) {
646 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
647 wfArrayToCGI( Skin
::getDynamicStylesheetQuery() ) );
653 * Store a file to a given destination.
655 * @param $srcPath String: source FS path, storage path, or virtual URL
656 * @param $dstZone String: destination zone
657 * @param $dstRel String: destination relative path
658 * @param $flags Integer: bitwise combination of the following flags:
659 * self::DELETE_SOURCE Delete the source file after upload
660 * self::OVERWRITE Overwrite an existing destination file instead of failing
661 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
662 * same contents as the source
663 * self::SKIP_LOCKING Skip any file locking when doing the store
664 * @return FileRepoStatus
666 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
667 $this->assertWritableRepo(); // fail out if read-only
669 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
670 if ( $status->successCount
== 0 ) {
678 * Store a batch of files
680 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
681 * @param $flags Integer: bitwise combination of the following flags:
682 * self::DELETE_SOURCE Delete the source file after upload
683 * self::OVERWRITE Overwrite an existing destination file instead of failing
684 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
685 * same contents as the source
686 * self::SKIP_LOCKING Skip any file locking when doing the store
687 * @return FileRepoStatus
689 public function storeBatch( array $triplets, $flags = 0 ) {
690 $this->assertWritableRepo(); // fail out if read-only
692 $status = $this->newGood();
693 $backend = $this->backend
; // convenience
695 $operations = array();
696 $sourceFSFilesToDelete = array(); // cleanup for disk source files
697 // Validate each triplet and get the store operation...
698 foreach ( $triplets as $triplet ) {
699 list( $srcPath, $dstZone, $dstRel ) = $triplet;
701 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
704 // Resolve destination path
705 $root = $this->getZonePath( $dstZone );
707 throw new MWException( "Invalid zone: $dstZone" );
709 if ( !$this->validateFilename( $dstRel ) ) {
710 throw new MWException( 'Validation error in $dstRel' );
712 $dstPath = "$root/$dstRel";
713 $dstDir = dirname( $dstPath );
714 // Create destination directories for this triplet
715 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
716 return $this->newFatal( 'directorycreateerror', $dstDir );
719 if ( $dstZone == 'deleted' ) {
720 $this->initDeletedDir( $dstDir );
723 // Resolve source to a storage path if virtual
724 $srcPath = $this->resolveToStoragePath( $srcPath );
726 // Get the appropriate file operation
727 if ( FileBackend
::isStoragePath( $srcPath ) ) {
728 $opName = ( $flags & self
::DELETE_SOURCE
) ?
'move' : 'copy';
731 if ( $flags & self
::DELETE_SOURCE
) {
732 $sourceFSFilesToDelete[] = $srcPath;
735 $operations[] = array(
739 'overwrite' => $flags & self
::OVERWRITE
,
740 'overwriteSame' => $flags & self
::OVERWRITE_SAME
,
744 // Execute the store operation for each triplet
745 $opts = array( 'force' => true );
746 if ( $flags & self
::SKIP_LOCKING
) {
747 $opts['nonLocking'] = true;
749 $status->merge( $backend->doOperations( $operations, $opts ) );
750 // Cleanup for disk source files...
751 foreach ( $sourceFSFilesToDelete as $file ) {
752 wfSuppressWarnings();
753 unlink( $file ); // FS cleanup
761 * Deletes a batch of files.
762 * Each file can be a (zone, rel) pair, virtual url, storage path.
763 * It will try to delete each file, but ignores any errors that may occur.
765 * @param $pairs array List of files to delete
766 * @param $flags Integer: bitwise combination of the following flags:
767 * self::SKIP_LOCKING Skip any file locking when doing the deletions
768 * @return FileRepoStatus
770 public function cleanupBatch( array $files, $flags = 0 ) {
771 $this->assertWritableRepo(); // fail out if read-only
773 $status = $this->newGood();
775 $operations = array();
776 foreach ( $files as $path ) {
777 if ( is_array( $path ) ) {
778 // This is a pair, extract it
779 list( $zone, $rel ) = $path;
780 $path = $this->getZonePath( $zone ) . "/$rel";
782 // Resolve source to a storage path if virtual
783 $path = $this->resolveToStoragePath( $path );
785 $operations[] = array( 'op' => 'delete', 'src' => $path );
787 // Actually delete files from storage...
788 $opts = array( 'force' => true );
789 if ( $flags & self
::SKIP_LOCKING
) {
790 $opts['nonLocking'] = true;
792 $status->merge( $this->backend
->doOperations( $operations, $opts ) );
798 * Import a file from the local file system into the repo.
799 * This does no locking nor journaling and overrides existing files.
800 * This function can be used to write to otherwise read-only foreign repos.
801 * This is intended for copying generated thumbnails into the repo.
803 * @param $src string File system path
804 * @param $dst string Virtual URL or storage path
805 * @return FileRepoStatus
807 final public function quickImport( $src, $dst ) {
808 return $this->quickImportBatch( array( array( $src, $dst ) ) );
812 * Purge a file from the repo. This does no locking nor journaling.
813 * This function can be used to write to otherwise read-only foreign repos.
814 * This is intended for purging thumbnails.
816 * @param $path string Virtual URL or storage path
817 * @return FileRepoStatus
819 final public function quickPurge( $path ) {
820 return $this->quickPurgeBatch( array( $path ) );
824 * Deletes a directory if empty.
825 * This function can be used to write to otherwise read-only foreign repos.
827 * @param $dir string Virtual URL (or storage path) of directory to clean
830 public function quickCleanDir( $dir ) {
831 $status = $this->newGood();
832 $status->merge( $this->backend
->clean(
833 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
839 * Import a batch of files from the local file system into the repo.
840 * This does no locking nor journaling and overrides existing files.
841 * This function can be used to write to otherwise read-only foreign repos.
842 * This is intended for copying generated thumbnails into the repo.
844 * @param $src Array List of tuples (file system path, virtual URL or storage path)
845 * @return FileRepoStatus
847 public function quickImportBatch( array $pairs ) {
848 $status = $this->newGood();
849 $operations = array();
850 foreach ( $pairs as $pair ) {
851 list ( $src, $dst ) = $pair;
852 $operations[] = array(
855 'dst' => $this->resolveToStoragePath( $dst ),
858 $this->backend
->prepare( array( 'dir' => dirname( $dst ) ) );
860 $status->merge( $this->backend
->doOperations( $operations,
861 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
868 * Purge a batch of files from the repo.
869 * This function can be used to write to otherwise read-only foreign repos.
870 * This does no locking nor journaling and is intended for purging thumbnails.
872 * @param $path Array List of virtual URLs or storage paths
873 * @return FileRepoStatus
875 public function quickPurgeBatch( array $paths ) {
876 $status = $this->newGood();
877 $operations = array();
878 foreach ( $paths as $path ) {
879 $operations[] = array(
881 'src' => $this->resolveToStoragePath( $path ),
882 'ignoreMissingSource' => true
885 $status->merge( $this->backend
->doOperations( $operations,
886 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
893 * Pick a random name in the temp zone and store a file to it.
894 * Returns a FileRepoStatus object with the file Virtual URL in the value,
895 * file can later be disposed using FileRepo::freeTemp().
897 * @param $originalName String: the base name of the file as specified
898 * by the user. The file extension will be maintained.
899 * @param $srcPath String: the current location of the file.
900 * @return FileRepoStatus object with the URL in the value.
902 public function storeTemp( $originalName, $srcPath ) {
903 $this->assertWritableRepo(); // fail out if read-only
905 $date = gmdate( "YmdHis" );
906 $hashPath = $this->getHashPath( $originalName );
907 $dstRel = "{$hashPath}{$date}!{$originalName}";
908 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
910 $result = $this->store( $srcPath, 'temp', $dstRel, self
::SKIP_LOCKING
);
911 $result->value
= $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
917 * Concatenate a list of files into a target file location.
919 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
920 * @param $dstPath String Target file system path
921 * @param $flags Integer: bitwise combination of the following flags:
922 * self::DELETE_SOURCE Delete the source files
923 * @return FileRepoStatus
925 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
926 $this->assertWritableRepo(); // fail out if read-only
928 $status = $this->newGood();
931 $deleteOperations = array(); // post-concatenate ops
932 foreach ( $srcPaths as $srcPath ) {
933 // Resolve source to a storage path if virtual
934 $source = $this->resolveToStoragePath( $srcPath );
935 $sources[] = $source; // chunk to merge
936 if ( $flags & self
::DELETE_SOURCE
) {
937 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
941 // Concatenate the chunks into one FS file
942 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
943 $status->merge( $this->backend
->concatenate( $params ) );
944 if ( !$status->isOK() ) {
948 // Delete the sources if required
949 if ( $deleteOperations ) {
950 $opts = array( 'force' => true );
951 $status->merge( $this->backend
->doOperations( $deleteOperations, $opts ) );
954 // Make sure status is OK, despite any $deleteOperations fatals
955 $status->setResult( true );
961 * Remove a temporary file or mark it for garbage collection
963 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
964 * @return Boolean: true on success, false on failure
966 public function freeTemp( $virtualUrl ) {
967 $this->assertWritableRepo(); // fail out if read-only
969 $temp = "mwrepo://{$this->name}/temp";
970 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
971 wfDebug( __METHOD__
.": Invalid temp virtual URL\n" );
974 $path = $this->resolveVirtualUrl( $virtualUrl );
976 return $this->cleanupBatch( array( $path ), self
::SKIP_LOCKING
)->isOK();
980 * Copy or move a file either from a storage path, virtual URL,
981 * or FS path, into this repository at the specified destination location.
983 * Returns a FileRepoStatus object. On success, the value contains "new" or
984 * "archived", to indicate whether the file was new with that name.
986 * @param $srcPath String: the source FS path, storage path, or URL
987 * @param $dstRel String: the destination relative path
988 * @param $archiveRel String: the relative path where the existing file is to
989 * be archived, if there is one. Relative to the public zone root.
990 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
991 * that the source file should be deleted if possible
992 * @return FileRepoStatus
994 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
995 $this->assertWritableRepo(); // fail out if read-only
997 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
998 if ( $status->successCount
== 0 ) {
1001 if ( isset( $status->value
[0] ) ) {
1002 $status->value
= $status->value
[0];
1004 $status->value
= false;
1011 * Publish a batch of files
1013 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1014 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1015 * that the source files should be deleted if possible
1016 * @return FileRepoStatus
1018 public function publishBatch( array $triplets, $flags = 0 ) {
1019 $this->assertWritableRepo(); // fail out if read-only
1021 $backend = $this->backend
; // convenience
1022 // Try creating directories
1023 $status = $this->initZones( 'public' );
1024 if ( !$status->isOK() ) {
1028 $status = $this->newGood( array() );
1030 $operations = array();
1031 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1032 // Validate each triplet and get the store operation...
1033 foreach ( $triplets as $i => $triplet ) {
1034 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1035 // Resolve source to a storage path if virtual
1036 $srcPath = $this->resolveToStoragePath( $srcPath );
1037 if ( !$this->validateFilename( $dstRel ) ) {
1038 throw new MWException( 'Validation error in $dstRel' );
1040 if ( !$this->validateFilename( $archiveRel ) ) {
1041 throw new MWException( 'Validation error in $archiveRel' );
1044 $publicRoot = $this->getZonePath( 'public' );
1045 $dstPath = "$publicRoot/$dstRel";
1046 $archivePath = "$publicRoot/$archiveRel";
1048 $dstDir = dirname( $dstPath );
1049 $archiveDir = dirname( $archivePath );
1050 // Abort immediately on directory creation errors since they're likely to be repetitive
1051 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1052 return $this->newFatal( 'directorycreateerror', $dstDir );
1054 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1055 return $this->newFatal( 'directorycreateerror', $archiveDir );
1058 // Archive destination file if it exists
1059 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1060 // Check if the archive file exists
1061 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1062 // unlinks the destination file if it exists. DB-based synchronisation in
1063 // publishBatch's caller should prevent races. In Windows there's no
1064 // problem because the rename primitive fails if the destination exists.
1065 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1066 $operations[] = array( 'op' => 'null' );
1069 $operations[] = array(
1072 'dst' => $archivePath
1075 $status->value
[$i] = 'archived';
1077 $status->value
[$i] = 'new';
1079 // Copy (or move) the source file to the destination
1080 if ( FileBackend
::isStoragePath( $srcPath ) ) {
1081 if ( $flags & self
::DELETE_SOURCE
) {
1082 $operations[] = array(
1088 $operations[] = array(
1094 } else { // FS source path
1095 $operations[] = array(
1100 if ( $flags & self
::DELETE_SOURCE
) {
1101 $sourceFSFilesToDelete[] = $srcPath;
1106 // Execute the operations for each triplet
1107 $opts = array( 'force' => true );
1108 $status->merge( $backend->doOperations( $operations, $opts ) );
1109 // Cleanup for disk source files...
1110 foreach ( $sourceFSFilesToDelete as $file ) {
1111 wfSuppressWarnings();
1112 unlink( $file ); // FS cleanup
1113 wfRestoreWarnings();
1120 * Deletes a directory if empty.
1122 * @param $dir string Virtual URL (or storage path) of directory to clean
1125 public function cleanDir( $dir ) {
1126 $this->assertWritableRepo(); // fail out if read-only
1128 $status = $this->newGood();
1129 $status->merge( $this->backend
->clean(
1130 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1136 * Checks existence of a a file
1138 * @param $file string Virtual URL (or storage path) of file to check
1141 public function fileExists( $file ) {
1142 $result = $this->fileExistsBatch( array( $file ) );
1147 * Checks existence of an array of files.
1149 * @param $files Array: Virtual URLs (or storage paths) of files to check
1150 * @return array|bool Either array of files and existence flags, or false
1152 public function fileExistsBatch( array $files ) {
1154 foreach ( $files as $key => $file ) {
1155 $file = $this->resolveToStoragePath( $file );
1156 $result[$key] = $this->backend
->fileExists( array( 'src' => $file ) );
1162 * Move a file to the deletion archive.
1163 * If no valid deletion archive exists, this may either delete the file
1164 * or throw an exception, depending on the preference of the repository
1166 * @param $srcRel Mixed: relative path for the file to be deleted
1167 * @param $archiveRel Mixed: relative path for the archive location.
1168 * Relative to a private archive directory.
1169 * @return FileRepoStatus object
1171 public function delete( $srcRel, $archiveRel ) {
1172 $this->assertWritableRepo(); // fail out if read-only
1174 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1178 * Move a group of files to the deletion archive.
1180 * If no valid deletion archive is configured, this may either delete the
1181 * file or throw an exception, depending on the preference of the repository.
1183 * The overwrite policy is determined by the repository -- currently LocalRepo
1184 * assumes a naming scheme in the deleted zone based on content hash, as
1185 * opposed to the public zone which is assumed to be unique.
1187 * @param $sourceDestPairs Array of source/destination pairs. Each element
1188 * is a two-element array containing the source file path relative to the
1189 * public root in the first element, and the archive file path relative
1190 * to the deleted zone root in the second element.
1191 * @return FileRepoStatus
1193 public function deleteBatch( array $sourceDestPairs ) {
1194 $this->assertWritableRepo(); // fail out if read-only
1196 // Try creating directories
1197 $status = $this->initZones( array( 'public', 'deleted' ) );
1198 if ( !$status->isOK() ) {
1202 $status = $this->newGood();
1204 $backend = $this->backend
; // convenience
1205 $operations = array();
1206 // Validate filenames and create archive directories
1207 foreach ( $sourceDestPairs as $pair ) {
1208 list( $srcRel, $archiveRel ) = $pair;
1209 if ( !$this->validateFilename( $srcRel ) ) {
1210 throw new MWException( __METHOD__
.':Validation error in $srcRel' );
1211 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1212 throw new MWException( __METHOD__
.':Validation error in $archiveRel' );
1215 $publicRoot = $this->getZonePath( 'public' );
1216 $srcPath = "{$publicRoot}/$srcRel";
1218 $deletedRoot = $this->getZonePath( 'deleted' );
1219 $archivePath = "{$deletedRoot}/{$archiveRel}";
1220 $archiveDir = dirname( $archivePath ); // does not touch FS
1222 // Create destination directories
1223 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1224 return $this->newFatal( 'directorycreateerror', $archiveDir );
1226 $this->initDeletedDir( $archiveDir );
1228 $operations[] = array(
1231 'dst' => $archivePath,
1232 // We may have 2+ identical files being deleted,
1233 // all of which will map to the same destination file
1234 'overwriteSame' => true // also see bug 31792
1238 // Move the files by execute the operations for each pair.
1239 // We're now committed to returning an OK result, which will
1240 // lead to the files being moved in the DB also.
1241 $opts = array( 'force' => true );
1242 $status->merge( $backend->doOperations( $operations, $opts ) );
1248 * Delete files in the deleted directory if they are not referenced in the filearchive table
1252 public function cleanupDeletedBatch( array $storageKeys ) {
1253 $this->assertWritableRepo();
1257 * Get a relative path for a deletion archive key,
1258 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1262 public function getDeletedHashPath( $key ) {
1264 for ( $i = 0; $i < $this->deletedHashLevels
; $i++
) {
1265 $path .= $key[$i] . '/';
1271 * If a path is a virtual URL, resolve it to a storage path.
1272 * Otherwise, just return the path as it is.
1274 * @param $path string
1276 * @throws MWException
1278 protected function resolveToStoragePath( $path ) {
1279 if ( $this->isVirtualUrl( $path ) ) {
1280 return $this->resolveVirtualUrl( $path );
1286 * Get a local FS copy of a file with a given virtual URL/storage path.
1287 * Temporary files may be purged when the file object falls out of scope.
1289 * @param $virtualUrl string
1290 * @return TempFSFile|null Returns null on failure
1292 public function getLocalCopy( $virtualUrl ) {
1293 $path = $this->resolveToStoragePath( $virtualUrl );
1294 return $this->backend
->getLocalCopy( array( 'src' => $path ) );
1298 * Get a local FS file with a given virtual URL/storage path.
1299 * The file is either an original or a copy. It should not be changed.
1300 * Temporary files may be purged when the file object falls out of scope.
1302 * @param $virtualUrl string
1303 * @return FSFile|null Returns null on failure.
1305 public function getLocalReference( $virtualUrl ) {
1306 $path = $this->resolveToStoragePath( $virtualUrl );
1307 return $this->backend
->getLocalReference( array( 'src' => $path ) );
1311 * Get properties of a file with a given virtual URL/storage path.
1312 * Properties should ultimately be obtained via FSFile::getProps().
1314 * @param $virtualUrl string
1317 public function getFileProps( $virtualUrl ) {
1318 $path = $this->resolveToStoragePath( $virtualUrl );
1319 return $this->backend
->getFileProps( array( 'src' => $path ) );
1323 * Get the timestamp of a file with a given virtual URL/storage path
1325 * @param $virtualUrl string
1326 * @return string|bool False on failure
1328 public function getFileTimestamp( $virtualUrl ) {
1329 $path = $this->resolveToStoragePath( $virtualUrl );
1330 return $this->backend
->getFileTimestamp( array( 'src' => $path ) );
1334 * Get the sha1 of a file with a given virtual URL/storage path
1336 * @param $virtualUrl string
1337 * @return string|bool
1339 public function getFileSha1( $virtualUrl ) {
1340 $path = $this->resolveToStoragePath( $virtualUrl );
1341 $tmpFile = $this->backend
->getLocalReference( array( 'src' => $path ) );
1345 return $tmpFile->getSha1Base36();
1349 * Attempt to stream a file with the given virtual URL/storage path
1351 * @param $virtualUrl string
1352 * @param $headers Array Additional HTTP headers to send on success
1353 * @return bool Success
1355 public function streamFile( $virtualUrl, $headers = array() ) {
1356 $path = $this->resolveToStoragePath( $virtualUrl );
1357 $params = array( 'src' => $path, 'headers' => $headers );
1358 return $this->backend
->streamFile( $params )->isOK();
1362 * Call a callback function for every public regular file in the repository.
1363 * This only acts on the current version of files, not any old versions.
1364 * May use either the database or the filesystem.
1366 * @param $callback Array|string
1369 public function enumFiles( $callback ) {
1370 $this->enumFilesInStorage( $callback );
1374 * Call a callback function for every public file in the repository.
1375 * May use either the database or the filesystem.
1377 * @param $callback Array|string
1380 protected function enumFilesInStorage( $callback ) {
1381 $publicRoot = $this->getZonePath( 'public' );
1382 $numDirs = 1 << ( $this->hashLevels
* 4 );
1383 // Use a priori assumptions about directory structure
1384 // to reduce the tree height of the scanning process.
1385 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++
) {
1386 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1387 $path = $publicRoot;
1388 for ( $hexPos = 0; $hexPos < $this->hashLevels
; $hexPos++
) {
1389 $path .= '/' . substr( $hexString, 0, $hexPos +
1 );
1391 $iterator = $this->backend
->getFileList( array( 'dir' => $path ) );
1392 foreach ( $iterator as $name ) {
1393 // Each item returned is a public file
1394 call_user_func( $callback, "{$path}/{$name}" );
1400 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1402 * @param $filename string
1405 public function validateFilename( $filename ) {
1406 if ( strval( $filename ) == '' ) {
1409 return FileBackend
::isPathTraversalFree( $filename );
1413 * Get a callback function to use for cleaning error message parameters
1417 function getErrorCleanupFunction() {
1418 switch ( $this->pathDisclosureProtection
) {
1420 case 'simple': // b/c
1421 $callback = array( $this, 'passThrough' );
1423 default: // 'paranoid'
1424 $callback = array( $this, 'paranoidClean' );
1430 * Path disclosure protection function
1432 * @param $param string
1435 function paranoidClean( $param ) {
1440 * Path disclosure protection function
1442 * @param $param string
1445 function passThrough( $param ) {
1450 * Create a new fatal error
1452 * @return FileRepoStatus
1454 public function newFatal( $message /*, parameters...*/ ) {
1455 $params = func_get_args();
1456 array_unshift( $params, $this );
1457 return MWInit
::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1461 * Create a new good result
1463 * @return FileRepoStatus
1465 public function newGood( $value = null ) {
1466 return FileRepoStatus
::newGood( $this, $value );
1470 * Checks if there is a redirect named as $title. If there is, return the
1471 * title object. If not, return false.
1474 * @param $title Title of image
1477 public function checkRedirect( Title
$title ) {
1482 * Invalidates image redirect cache related to that image
1483 * Doesn't do anything for repositories that don't support image redirects.
1486 * @param $title Title of image
1488 public function invalidateImageRedirect( Title
$title ) {}
1491 * Get the human-readable name of the repo
1495 public function getDisplayName() {
1496 // We don't name our own repo, return nothing
1497 if ( $this->isLocal() ) {
1500 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1501 return wfMessageFallback( 'shared-repo-name-' . $this->name
, 'shared-repo' )->text();
1505 * Returns true if this the local file repository.
1509 public function isLocal() {
1510 return $this->getName() == 'local';
1514 * Get a key on the primary cache for this repository.
1515 * Returns false if the repository's cache is not accessible at this site.
1516 * The parameters are the parts of the key, as for wfMemcKey().
1521 public function getSharedCacheKey( /*...*/ ) {
1526 * Get a key for this repo in the local cache domain. These cache keys are
1527 * not shared with remote instances of the repo.
1528 * The parameters are the parts of the key, as for wfMemcKey().
1532 public function getLocalCacheKey( /*...*/ ) {
1533 $args = func_get_args();
1534 array_unshift( $args, 'filerepo', $this->getName() );
1535 return call_user_func_array( 'wfMemcKey', $args );
1539 * Get an temporary FileRepo associated with this repo.
1540 * Files will be created in the temp zone of this repo and
1541 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1542 * It will have the same backend as this repo.
1544 * @return TempFileRepo
1546 public function getTempRepo() {
1547 return new TempFileRepo( array(
1548 'name' => "{$this->name}-temp",
1549 'backend' => $this->backend
,
1552 'container' => $this->zones
['temp']['container'],
1553 'directory' => $this->zones
['temp']['directory']
1556 'container' => $this->zones
['thumb']['container'],
1557 'directory' => ( $this->zones
['thumb']['directory'] == '' )
1559 : $this->zones
['thumb']['directory'] . '/temp'
1562 'url' => $this->getZoneUrl( 'temp' ),
1563 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1564 'hashLevels' => $this->hashLevels
// performance
1569 * Get an UploadStash associated with this repo.
1571 * @return UploadStash
1573 public function getUploadStash() {
1574 return new UploadStash( $this );
1578 * Throw an exception if this repo is read-only by design.
1579 * This does not and should not check getReadOnlyReason().
1582 * @throws MWException
1584 protected function assertWritableRepo() {}
1588 * FileRepo for temporary files created via FileRepo::getTempRepo()
1590 class TempFileRepo
extends FileRepo
{
1591 public function getTempRepo() {
1592 throw new MWException( "Cannot get a temp repo from a temp repo." );